package com.tuanchau.android.englishtooltip.ui.widget;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.tuanchau.android.englishtooltip.Global;
import com.tuanchau.android.englishtooltip.service.UpdateService;

public class TooltipWidget extends AppWidgetProvider {

	public static final String ACTION_SPEECH = "speech_word";

	private PendingIntent piService;

	@Override
	public void onUpdate(final Context context,
			final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {
		super.onUpdate(context, appWidgetManager, appWidgetIds);
		initClickListener(context, appWidgetManager, appWidgetIds);
	}

	private void initClickListener(Context context,
			AppWidgetManager appWidgetManager, int[] appWidgetIds) {

		// ----------------- update word------------------
		final AlarmManager am = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		final Calendar TIME = Calendar.getInstance();

		TIME.set(Calendar.MINUTE, 0);
		TIME.set(Calendar.SECOND, 0);
		TIME.set(Calendar.MILLISECOND, 0);

		Intent sintent = new Intent(context.getApplicationContext(),
				UpdateService.class);
		if (piService == null) {
			piService = PendingIntent.getService(context,
					Global.REQUEST_TO_SERVICE, sintent,
					PendingIntent.FLAG_CANCEL_CURRENT);
		}
		am.setRepeating(AlarmManager.RTC, TIME.getTime().getTime(), 1000,
				piService);

	}

	@Override
	public void onReceive(Context context, Intent intent) {

		super.onReceive(context, intent);

		String action = intent.getAction();
		Log.d("Widget", "con heo : action = " + action);
		if (action != null) {
			if (action.equals(AppWidgetManager.ACTION_APPWIDGET_DELETED)) {
				Intent sintent = new Intent(context.getApplicationContext(),
						UpdateService.class);
				context.stopService(sintent);
				final AlarmManager am = (AlarmManager) context
						.getSystemService(Context.ALARM_SERVICE);
				am.cancel(piService);
			}
		}
	}

}
